<script lang="jsx" setup>
import { computed, onUnmounted, ref } from 'vue';
import { useElementSize } from '@vueuse/core';
import dayjs from 'dayjs';
import { useRouteQuery } from '@vueuse/router';
import {
  getHotMeltMachineLatestReadCode,
  getYhStructureByLot,
  getYhStructureByLotNo,
  reportYhStructure,
  sendEqpAlarm
} from '@/service/api/modules/issuance-management/hot-melt-machine-down';
import useResetTableRef from '@/hooks/common/resetTableRef';
import SearchForm from './modules/form.vue';
import DownTable from './modules/down-table.vue';

const isInput = useRouteQuery('isInput');

console.log('isInput', isInput);

const [tasList, resetTasList] = useResetTableRef([
  {
    name: '熔合',
    index: 1,
    list: []
  }
]);

const active = ref(1);

const baseUrl = ref('/dev-api/');
const machineNo = window.$utils.getRouteParams();
console.log('当前机台号：', machineNo);
// lot号 生产型号 客户代码
const model = ref({
  lotNo: null,
  machineNo
});

const fusionData = ref({
  lotNo: null,
  prodNo: null,
  custNo: null,
  image: null
});

const contentRef = ref(null);
const { height } = useElementSize(contentRef);
const hiddenImgRef = ref(null);

function getHiddenImgHeight() {
  return hiddenImgRef.value.naturalHeight;
}

function getImgScaleY() {
  // img 背景图高度
  const imgHeight = height.value - 151;
  // img原始高度
  const naturalHeight = getHiddenImgHeight();
  console.log('imgHeight / naturalHeight', imgHeight / naturalHeight);
  return imgHeight / naturalHeight;
}

// 图片缩放比例，为是图片铺满
const imgScaleY = ref(1);
// 获取基础url
function getBaseUrl() {
  if (location.hostname === 'localhost') {
    baseUrl.value = 'http://192.168.166.166/dev-api/';
    return;
  }
  baseUrl.value = '/dev-api/';
}
getBaseUrl();

function deepCloneArray(arr) {
  const clone = [];
  arr.forEach((item, index) => {
    if (Array.isArray(item)) {
      clone[index] = deepCloneArray(item);
    } else if (item instanceof Object) {
      clone[index] = { ...item };
    } else {
      clone[index] = item;
    }
  });
  return clone;
}

const scanCodeTime = ref(''); // 扫码时间
// 获取层结构
function getList(isReaded = true) {
  let pro;
  if (isInput.value) {
    pro = getYhStructureByLotNo({ lotNo: model.value.lotNo });
  } else {
    pro = getYhStructureByLot({ eqpId: model.value.machineNo });
  }

  pro.then(({ data, error }) => {
    if (!error) {
      scanCodeTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss');
      // scanCodeTime.value = '2024-05-01 10:00:00';
      // list.value = data.list.map(item => {
      //   return {
      //     state: null,
      //     proNoBase: null,
      //     ...item
      //   };
      // });

      const floorList = data.list.map(item => {
        return {
          state: null,
          proNoBase: null,
          ...item
        };
      });

      tasList.value[tasList.value.length - 1].list = floorList;

      console.log('层级结构：', tasList.value);

      fusionData.value.lotNo = model.value.lotNo;
      fusionData.value.prodNo = data.prodNo;
      fusionData.value.custNo = data.custNo;
      fusionData.value.lotNo = data.lotNo;
      if (!isInput.value) {
        model.value.lotNo = data.pnlCode;
      }
      if (data.image) {
        fusionData.value.image = baseUrl.value + data.image;
      }
      // 获取完后立即执行获取最新读码数据
      // getNewestReadCode();

      // 5秒后开始获取最新读码数据
      startGetNewestReadCode();
    }
  });
}

// 获取获取最新的读码数据
function getNewestReadCode() {
  getHotMeltMachineLatestReadCode({
    startTime: scanCodeTime.value,
    eqpId: model.value.machineNo
  }).then(({ data, error }) => {
    if (!error && data.prodNo) {
      getUnCheckedYinBan(data);
    }
  });
}

let getNewestReadCodeTimer = null; // 定时获取最新读码数据的定时器
const delayTime = 1000 * 2; // 5秒后开始获取最新读码数据
function startGetNewestReadCode() {
  getNewestReadCodeTimer = setInterval(() => {
    getNewestReadCode();
  }, delayTime);
}

// 停止获取最新读码数据
function stopGetNewestReadCode() {
  clearInterval(getNewestReadCodeTimer);
  getNewestReadCodeTimer = null;
}

// 获取状态不为1芯板的索引
function getXinBanIndex() {
  return tasList.value[tasList.value.length - 1].list.findIndex(item => item.state === null && item.data1 === '芯板');
}

// 获取状态为0芯板的索引
function getXinBanNGIndex() {
  return tasList.value[tasList.value.length - 1].list.findIndex(item => item.state === 0 && item.data1 === '芯板');
}

function getXinBanListHasPnlCode(pnlCode) {
  return tasList.value[tasList.value.length - 1].list.some(item => {
    if (item.data1 === '芯板') {
      console.log(item);
    }
    return item.data1 === '芯板' && item.pnlCode === pnlCode;
    // item => item.data1 === '芯板' && item.proNoBase === prodNo
  });
}
// 1241107017001

const isAlarm = ref(false); // 是否警告
const alarmIndex = ref(null); // 警告索引
// 获取未校验状态的芯板
function getUnCheckedYinBan(data) {
  const floors = tasList.value[tasList.value.length - 1].list.filter(item => item.data1 === '芯板').length;
  const index = getXinBanIndex();
  console.log(index);

  // 没有找到未校验状态的芯板
  if (index === -1) {
    stopGetNewestReadCode();
    return;
  }
  const item = tasList.value[tasList.value.length - 1].list[index];

  // 芯板数量大于1
  if (floors > 1) {
    const itemProNo = `${item.prodNo}-${item.data4}`;
    const isHasPnlcode = getXinBanListHasPnlCode(data.pnlCode);
    if (isHasPnlcode) return;
    //! important 这个赋值提到前面有问题
    if (index > 0) {
      tasList.value[tasList.value.length - 1].list[index].pnlCode = data?.lotNo;
      tasList.value[tasList.value.length - 1].list[index].proNoBase = data?.prodNo;
      tasList.value[tasList.value.length - 1].list[index].pnlCode = data.pnlCode;
      tasList.value[tasList.value.length - 1].list[index].lotNo = data.lotNo;
    }
    // 开始校验层级信息
    console.log(itemProNo);
    console.log(
      'tasList.value[tasList.value.length - 1].list[index]',
      tasList.value[tasList.value.length - 1].list[index]
    );
    if (itemProNo === data.prodNo) {
      // if (index > 0) {
      //   list.value[index].pnlCode = data?.lotNo;
      //   list.value[index].proNoBase = data?.prodNo;
      //   list.value[index].pnlCode = data.pnlCode;
      // }
      // 校验通过
      item.state = 1;
    } else {
      // 校验失败
      notPass(index);
    }
  } else {
    // 芯板数量等于1，直接开始校验层级信息
    // eslint-disable-next-line no-lonely-if
    if (index > 0) {
      tasList.value[tasList.value.length - 1].list[index].pnlCode = data?.lotNo;
      tasList.value[tasList.value.length - 1].list[index].proNoBase = data?.prodNo;
      tasList.value[tasList.value.length - 1].list[index].pnlCode = data.pnlCode;
      tasList.value[tasList.value.length - 1].list[index].lotNo = data.lotNo;
    }
    if (data.prodNo.includes(item.prodNo)) {
      item.state = 1;
    } else {
      // 校验失败
      notPass(index);
    }
  }
}

function notPass(index) {
  // 停止获取最新读码数据
  alarmIndex.value = index;
  tasList.value[tasList.value.length - 1].list[index].state = 0;
  console.log('停止2');
  stopGetNewestReadCode();
  // 弹出提示框
  window.$modal.error({
    title: '提示',
    content: '芯板放置不正确，请重新放置!'
  });

  // 发送报警
  reportAlarm();
}

// 机台报警
function reportAlarm() {
  // 如果已经报警了就不要进行报警了
  if (isAlarm.value) return;
  sendEqpAlarm({ eqpId: model.value.machineNo, alarmType: 1 })
    .then(({ error }) => {
      if (!error) {
        console.log('报警成功');
        stopGetNewestReadCode();
      }
    })
    .finally(() => {
      isAlarm.value = true;
    });
}

// 取消机台报警
const cancelAlarmObj = {
  title: '是否取消报警!',
  content: null,
  type: 'warning',
  onOk: () => {
    sendEqpAlarm({ eqpId: model.value.machineNo, alarmType: 0 }).then(({ error }) => {
      if (!error) {
        window.$message.success('取消报警成功!');
        isAlarm.value = false;
        tasList.value[tasList.value.length - 1].list[alarmIndex.value].state = null;
        tasList.value[tasList.value.length - 1].list[alarmIndex.value].pnlCode = null;
        tasList.value[tasList.value.length - 1].list[alarmIndex.value].proNoBase = null;
        startGetNewestReadCode();
      }
    });
  }
};

const fusionLoading = ref(false);
const fusionConfirmObj = {
  title: '是否确认进行熔合?',
  onOk: () => {
    fusionLoading.value = true;
    const params = tasList.value.map(m => {
      return m.list.map(item => {
        return {
          ...item,
          fusionProdNo: fusionData.value.prodNo,
          prodNo: item.proNoBase,
          eqpId: machineNo
        };
      });
    });
    reportYhStructure(params)
      .then(({ error }) => {
        if (!error) {
          window.$message.success('熔合成功!');
          active.value = tasList.value.length;
          resetTasList();
          reset();
        }
      })
      .finally(() => {
        fusionLoading.value = false;
      });
  }
};

function reset() {
  stopGetNewestReadCode();
  resetTasList();
  isAlarm.value = false;
  fusionData.value = {
    lotNo: null,
    prodNo: null,
    custNo: null,
    image: null
  };
  imgScaleY.value = 1;
  getList();
}

// 暂存
async function handleStaging() {
  stopGetNewestReadCode();
  tasList.value.push({
    name: '熔合',
    index: tasList.value.length + 1,
    list: []
  });

  console.log('tasList.value', tasList.value);
  await getList(false);
  active.value = tasList.value.length;
}

// 所有芯板都校验完成
const isOk = computed(() => {
  if (!tasList.value[tasList.value.length - 1].list.length) {
    stopGetNewestReadCode();
    return false;
  }
  const flag = tasList.value[tasList.value.length - 1].list
    .filter(item => item.data1 === '芯板')
    .every(item => item.state === 1);
  if (flag) {
    stopGetNewestReadCode();
    return true;
  }
  return false;
});

onUnmounted(() => {
  stopGetNewestReadCode();
});
</script>

<template>
  <div class="hot-melt-machine-down-page jl-main-page min-h-500px flex-col-stretch overflow-hidden lt-sm:overflow-auto">
    <div ref="contentRef" class="content h-full flex">
      <div class="laminated-diagram h-full w-500px">
        <div class="msg h-151px w-100% flex-center">
          <ADescriptions title="热熔机熔合纠错">
            <ADescriptionsItem label="lot号" :span="3">
              {{ fusionData.lotNo }}
            </ADescriptionsItem>
            <ADescriptionsItem label="生产型号" :span="3">
              {{ fusionData.prodNo }}
            </ADescriptionsItem>
            <ADescriptionsItem label="客户代码" :span="3">{{ fusionData.custNo }}</ADescriptionsItem>
          </ADescriptions>
        </div>
        <div class="laminated-diagram-img flex-center">
          <img
            v-show="false"
            ref="hiddenImgRef"
            :src="fusionData.image"
            alt=""
            class="hidden-img"
            @load="imgScaleY = getImgScaleY()"
          />
          <div
            v-if="fusionData.image"
            class="img"
            :style="{
              transform: `scaleY(${imgScaleY})`,
              backgroundImage: `url(${fusionData.image})`
            }"
          ></div>
          <div v-else class="no-data h-full w-full flex-center"><AEmpty description="暂无层叠图" /></div>
        </div>
      </div>
      <div class="detail h-full">
        <div class="lotNo-form h-100px w-100% flex-center">
          <SearchForm v-model:model="model" class="w-full p-20px" @search="getList" />
        </div>
        <div class="detail-table">
          <ATabs v-model:activeKey="active" type="card" size="large">
            <ATabPane v-for="item in tasList" :key="item.index" :tab="`${item.name}${item.index}`">
              <DownTable v-model:list="item.list" class="h-full"></DownTable>
            </ATabPane>
          </ATabs>
        </div>
      </div>
    </div>
    <div class="footer w-full flex-center">
      <AButton type="primary" class="mr-30px" size="large" :disabled="!isOk" @click="handleStaging">暂存</AButton>
      <AButton
        v-confirm="fusionConfirmObj"
        type="primary"
        class="mr-30px"
        size="large"
        :loading="fusionLoading"
        :disabled="!isOk"
      >
        熔合
      </AButton>
      <AButton type="default" size="large" class="mr-30px" @click="reset">重置</AButton>
      <AButton v-if="isAlarm" v-confirm="cancelAlarmObj" type="primary" size="large">预警撤销</AButton>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.table-cell {
  color: rgba(0, 0, 0, 0.25);
  background-color: rgba(0, 0, 0, 0.04);
  border-color: #d9d9d9;
  display: inline-block;
  border-radius: 8px;
  padding: 0 8px;
}

.hot-melt-machine-down-page {
  .content {
    height: calc(100% - 100px);
    background-color: #fff;
    .border-right {
      border-right: 3px solid #247cfe;
    }

    .title {
      font-size: 16px;
      font-weight: bold;
      line-height: 40px;
      border-bottom: 1px solid #d9d9d9;
      background-color: #fff;
    }

    .laminated-diagram {
      overflow: hidden;
      .laminated-diagram-img {
        height: calc(100% - 151px);
        padding-top: 10px;

        .img {
          width: 444px;
          height: 100%;
          //background: url('/public/sysDrawProdDraw.jfif');
          background-repeat: no-repeat;
          transform-origin: top;
        }
      }

      .msg {
        padding-left: 5px;
        :deep(.ant-descriptions) {
          .ant-descriptions-item {
            padding-bottom: 5px;
          }
          .ant-descriptions-header {
            margin-bottom: 0;
            .ant-descriptions-title {
              color: #646cff;
              font-size: 24px;
              font-weight: bold;
            }
          }
          .ant-descriptions-item-label,
          .ant-descriptions-item-content {
            font-size: 20px;
            font-weight: bold;
          }
        }
      }
    }

    .detail {
      width: calc(100% - 500px);
      border-left: 3px solid #247cfe;
      .list {
        overflow-y: auto;
        .item {
          justify-content: space-between;
          line-height: 40px;
          font-size: 32px;
          font-weight: bold;
          // border-bottom: 1px solid #d9d9d9;
          &.flex-start {
            justify-content: flex-start;
          }
        }
      }
    }

    .detail-table {
      padding-top: 8px;

      overflow-y: auto;
      border-top: 3px solid #247cfe;
      height: calc(100% - 100px);

      :deep(.ant-tabs) {
        height: 100%;

        .ant-tabs-nav-wrap {
          .ant-tabs-tab .ant-tabs-tab-btn {
            font-size: 24px;
          }
        }

        .ant-tabs-content-holder {
          height: calc(100% - 56px);
          .ant-tabs-content {
            height: 100%;
            .ant-tabs-tabpane {
              height: 100%;
            }
          }
        }
      }
    }

    table {
      border-collapse: collapse;
    }
  }

  .tbody {
    height: calc(100% - 46px);
    overflow-y: auto;
  }
  .thead th {
    position: sticky;
    top: 0;
    z-index: 999;
    background-color: #fff;
  }

  .footer {
    height: 100px;
    border-top: 3px solid #247cfe;
    background-color: #fff;
  }
}
</style>
